<template>
  <div class="cancel-page">
    <!-- 顶部导航 -->
    <div class="page-header">
      <el-button icon="ArrowLeft" size="small" @click="handleGoBack" class="back-btn" />
      <h2 class="page-title">订单取消</h2>
    </div>

    <!-- 状态提示 -->
    <el-alert title="提示" type="warning" :closable="false" class="status-alert">
      您正在取消已支付订单，将根据酒店规则计算退款金额
    </el-alert>

    <!-- 订单信息 -->
    <el-card class="info-card">
      <div class="order-info">
        <h3 class="hotel-name">{{ hotelInfo.hotelName }}</h3>
        <p class="hotel-address">{{ hotelInfo.province }}{{ hotelInfo.city }}{{ hotelInfo.county }}{{ hotelInfo.street }}</p>

        <div class="info-row">
          <span class="info-label">订单号：</span>
          <span class="info-value">{{ order.orderNumber }}</span>
        </div>

        <div class="info-row">
          <span class="info-label">入住时间：</span>
          <span class="info-value">
            {{ formatDate(orderDetail.checkIn) }} - {{ formatDate(orderDetail.checkOut) }}
            （共{{ getStayNights() }}晚）
          </span>
        </div>

        <div class="info-row">
          <span class="info-label">房型：</span>
          <span class="info-value">{{ roomType.roomtypeName }} × {{ orderDetail.roomQuantity }}间</span>
        </div>

        <div class="info-row">
          <span class="info-label">实付金额：</span>
          <span class="info-value price-red">¥{{ paymentRecord.amount.toFixed(2) }}</span>
        </div>
      </div>
    </el-card>

    <!-- 取消规则 -->
    <el-card class="rule-card" header="取消规则">
      <div
        class="rule-item"
        :class="{ 'matched-rule': rule.cancelId === matchedRule.cancelId }"
        v-for="rule in cancelRules"
        :key="rule.cancelId"
      >
        <div class="rule-header">
          <span class="rule-type">{{ rule.cancelType }}</span>
          <span class="rule-time">
            {{ rule.cancelDays >= 0 ? (rule.cancelDays === 0 ? '入住当天' : `提前${rule.cancelDays}天`) : '提前退房' }}
          </span>
        </div>
        <div class="rule-content">
          <p>{{ rule.ruleDesc }}</p>
          <p class="fee-rate">
            违约金比例：{{ rule.feeRate > 0 ? (rule.feeRate * 100).toFixed(0) + '%' : '0%（免费取消）' }}
          </p>
        </div>
      </div>
    </el-card>

    <!-- 费用计算 -->
    <el-card class="calculation-card" header="取消费用计算">
      <div class="calc-item">
        <span class="calc-label">当前距入住：</span>
        <span class="calc-value">{{ daysDiff }}天</span>
      </div>
      <div class="calc-item">
        <span class="calc-label">适用规则：</span>
        <span class="calc-value">{{ matchedRule.ruleDesc }}</span>
      </div>
      <div class="calc-item">
        <span class="calc-label">违约金：</span>
        <span class="calc-value price-red">¥{{ penaltyAmount.toFixed(2) }}</span>
      </div>
      <div class="calc-item">
        <span class="calc-label">可退款金额：</span>
        <span class="calc-value price-green">¥{{ refundAmount.toFixed(2) }}</span>
      </div>
      <el-alert type="info" size="small" class="refund-note" :closable="false" description="退款将在3-7个工作日内原路退回" />
    </el-card>

    <!-- 操作按钮 -->
    <div class="btn-group">
      <el-button @click="toOrderDetail" class="back-button">返回订单详情</el-button>
      <el-button type="danger" @click="showDialog = true" :disabled="isProcessing" class="confirm-button">
        确认取消订单
      </el-button>
    </div>

    <!-- 确认弹窗 -->
    <el-dialog v-model="showDialog" title="确认取消订单？" width="300px">
      <div class="dialog-content">
        <p>订单号：{{ order.orderNumber }}</p>
        <p>违约金：¥{{ penaltyAmount.toFixed(2) }}</p>
        <p>可退款：¥{{ refundAmount.toFixed(2) }}</p>
        <el-alert type="warning" size="small" :closable="false" class="dialog-warning" description="订单取消后不可恢复，请谨慎操作" />
      </div>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="danger"
        @click="() => {console.log('点击确认按钮');handleConfirmCancel()}" :loading="isProcessing">确认取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { getOrderCancelRules, cancelPaidOrder, ordersDetail } from '@/api/orders.js'


const route = useRoute()
const router = useRouter()

const orderId = ref(route.query.orderId)

onMounted(() => {
  if (!orderId.value) {
    console.warn('URL 参数缺少 orderId:', route.query)
  } else {
    loadOrderData()
    loadCancelRules()
  }
})

// 响应式数据
const order = reactive({})
const orderDetail = reactive({ checkIn: '', checkOut: '', roomtypeId: null, roomQuantity: 1 })
const hotelInfo = reactive({ hotelName: '', province: '', city: '', county: '', street: '' })
const roomType = reactive({ roomtypeName: '' })
const paymentRecord = reactive({ amount: 0 })
const cancelRules = ref([])
const matchedRule = reactive({})
const daysDiff = ref(0)
const penaltyAmount = ref(0)
const refundAmount = ref(0)
const showDialog = ref(false)
const isProcessing = ref(false)

// 获取订单详情
const loadOrderData = async () => {
  try {
    const res = await ordersDetail(orderId.value)
    if (res.data.code === 200) {
      const data = res.data.data
      console.log(data)

      order.orderNumber = data.orderNumber
      order.orderId = data.orderId
      orderDetail.checkIn = data.checkIn
      orderDetail.checkOut = data.checkOut
      orderDetail.roomQuantity = data.roomQuantity
      orderDetail.roomtypeId = data.roomtypeId
      hotelInfo.hotelName = data.hotelName
      hotelInfo.street = data.hotelAddress
      roomType.roomtypeName = data.roomtypeName
      paymentRecord.amount = data.orderPrice

      calculateDaysDifference()
      matchCancelRule()
      calculatePenalty()
    }
  } catch (err) {
    ElMessage.error('获取订单详情失败')
    console.error(err)
  }
}

// 获取取消规则
const loadCancelRules = async () => {
  try {
    const res = await getOrderCancelRules()
    if (res.data.code === 200) {
      cancelRules.value = res.data.data
      matchCancelRule()
      calculatePenalty()
    } else {
      ElMessage.error(res.data.message || '获取取消规则失败')
    }
  } catch (err) {
    ElMessage.error('获取取消规则失败')
    console.error(err)
  }
}

// 计算距入住天数
const calculateDaysDifference = () => {
  if (!orderDetail.checkIn) {
    daysDiff.value = 0
    return
  }

  // 将入住日期和今天都置为当天0点，避免小时差导致向下取整
  const checkInDate = dayjs(orderDetail.checkIn).startOf('day')
  const today = dayjs().startOf('day')

  // 计算天数差
  daysDiff.value = checkInDate.diff(today, 'day')

  // 负数统一归零
  if (daysDiff.value < 0) daysDiff.value = 0
}

// 匹配取消规则
const matchCancelRule = () => {
  if (!cancelRules.value.length) return
  const sortedRules = [...cancelRules.value].sort((a, b) => b.cancelDays - a.cancelDays)
  const found = sortedRules.find(rule => daysDiff.value >= rule.cancelDays)
  Object.assign(matchedRule, found || sortedRules[sortedRules.length - 1])
}

// 计算违约金与退款金额
const calculatePenalty = () => {
  const total = paymentRecord.amount || 0
  const rate = matchedRule.feeRate || 0
  penaltyAmount.value = Number((total * rate).toFixed(2))
  refundAmount.value = Number((total - penaltyAmount.value).toFixed(2))
}

// 格式化日期
const formatDate = date => dayjs(date).format('YYYY-MM-DD')

// 计算入住晚数
const getStayNights = () => dayjs(orderDetail.checkOut).diff(orderDetail.checkIn, 'day')

// 返回
const handleGoBack = () => router.back()


// 确认取消
const handleConfirmCancel = async () => {

  if (!orderId.value) {
    ElMessage.error('订单ID不存在，无法取消')
    return
  }

  isProcessing.value = true
  try {
    console.log('cancel orderId = ' ,orderId.value)


    const res = await cancelPaidOrder(orderId.value)
    ElMessage.success(res.data.message || '订单已取消，将按规则退款')
    router.push(`/orderDetail/${order.orderId}`)
  } catch (err) {
    ElMessage.error('取消失败，请稍后重试')
    console.error(err)
  } finally {
    isProcessing.value = false
  }
}

const toOrderDetail = () => router.push(`/orderDetail/${orderId.value}`)


</script>

<style scoped>
.cancel-page {
  padding: 24px;
  max-width: 960px;
  margin: 20px auto;
  background-color: #f9f9f9;
  min-height: 100vh;
  border-radius: 8px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #eee;
}

.back-btn {
  margin-right: 12px;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  margin: 0;
}

.status-alert {
  margin-bottom: 16px;
}

.info-card,
.rule-card,
.calculation-card {
  margin-bottom: 16px;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
}

.order-info {
  padding: 12px 0;
}

.hotel-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 500;
}

.hotel-address {
  color: #666;
  margin: 0 0 16px 0;
  font-size: 14px;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-label {
  color: #666;
  width: 90px;
  flex-shrink: 0;
}

.info-value {
  flex-grow: 1;
}

.rule-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 4px;
  background-color: #f9f9f9;
}

.rule-item.matched-rule {
  background-color: #fff8f0;
  border: 1px solid #ffe7cc;
}

.rule-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-weight: 500;
}

.rule-type {
  color: #e67700;
}

.rule-content {
  font-size: 14px;
}

.fee-rate {
  margin-top: 4px;
  color: #d93025;
}

.calc-item {
  display: flex;
  justify-content: space-between;
  padding: 6px 0;
  border-bottom: 1px dashed #eee;
}

.calc-label {
  color: #666;
}

.refund-note {
  margin-top: 12px;
}

.btn-group {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.back-button,
.confirm-button {
  flex: 1;
  padding: 10px 0;
}

.price-red {
  color: #d93025;
  font-weight: 500;
}

.price-green {
  color: #10b981;
  font-weight: 500;
}

.dialog-content {
  font-size: 14px;
  line-height: 1.6;
}

.dialog-warning {
  margin-top: 12px;
}
</style>
